package com.example.graduatetest.view.model;

import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.graduatetest.R;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.bean.Score;
import com.example.graduatetest.callback.ScoreListCallBack;
import com.example.graduatetest.callback.StringCallBack;
import com.example.graduatetest.callback.TestNameList;
import com.example.graduatetest.databinding.ActivityScoreAllBinding;
import com.example.graduatetest.model.ScoreModel;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;

import java.util.ArrayList;
import java.util.List;


public class ScoreAllViewModel extends ViewModel {
    private Activity activity;
    private ActivityScoreAllBinding binding;
    private Classes ownClass;
    private Handler handler = new Handler();
    private PieChart pie;
    private int one=0,two=0,three=0,four=0,five=0;
    private float sum = 0;
    private float avg;
    private String format;
    private String test_name;
    private String[] strArray;
    List<PieEntry> pieDataList;
    List<Integer> colors = new ArrayList<>();
    List<Score> scores = new ArrayList<>();

    public void init(Activity activity,ActivityScoreAllBinding binding,Classes ownClass){
        this.activity = activity;
        this.binding = binding;
        this.ownClass = ownClass;
        pie = binding.pieChart;
        toolbarInit();
        initClick();
        initView();
    }


    //初始化toolbar
    private void toolbarInit(){
        Toolbar toolbar = binding.toolbar13;
        toolbar.setTitle("成绩统计");
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });
    }

    //初始化View
    private void initView(){
        binding.textClassName.setText(ownClass.getName());
        binding.textTeacherName.setText(ownClass.getTeacher());
        binding.textPeopleNumber.setText(String.valueOf(ownClass.getNumber()));
        binding.pieChart.setVisibility(View.GONE);
        ScoreModel.selectTestName(ownClass.getId(), new TestNameList() {
            @Override
            public void onSuccess(List<String> strList) {
                if(strList != null){
                    strArray = new String[strList.size()];
                    for (int i = 0; i <strList.size() ; i++) {
                        strArray[i] = strList.get(i);
                    }

                }else{
                    strArray = new String[]{"暂无考试"};
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateUI();
                    }
                });
            }

            @Override
            public void onFailed() {
                strArray = new String[]{"网络错误"};
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateUI();
                    }
                });
                Log.e("haha", "网络错误");
            }
        });
    }

    //更新spinner
    private void updateUI(){
        ArrayAdapter<String> adapter=new ArrayAdapter<>(activity,android.R.layout.simple_spinner_item, strArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinner.setAdapter(adapter);
        binding.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                TextView tv = (TextView)view;
                // 修改样式属性
                tv.setTextSize(20f);
                tv.setTextColor(Color.parseColor("#FDCB40"));
                tv.setGravity(Gravity.START);
                test_name = tv.getText().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO
            }
        });

    }

    //评定等级
    private void setData(int number){
        if(format.equals("百分制")){
            if(number < 60){
                one++;
            }else if(number < 70){
                two++;
            }else if(number < 80){
                three++;
            }else if(number < 90){
                four++;
            }else{
                five++;
            }
        }else{
            if(number < 90){
                one++;
            }else if(number < 100){
                two++;
            }else if(number < 120){
                three++;
            }else if(number < 140){
                four++;
            }else{
                five++;
            }
        }
    }
    //设置饼图
    private void setPieChartAndAvg(List<Score> list){
        binding.pieChart.setVisibility(View.VISIBLE);
        pieDataList=new ArrayList<>();
        //设置颜色
        colors.add(Color.parseColor("#EC7259"));
        colors.add(Color.parseColor("#FDCD08"));
        colors.add(Color.parseColor("#18AEBD"));
        colors.add(Color.parseColor("#94A6FA"));
        colors.add(Color.parseColor("#3559F4"));

        format = list.get(0).getScore_format();
        sum = 0;
        for (Score score: list) {
           setData(score.getScore());
           sum += score.getScore();
        }
        avg = sum / list.size();
        binding.textAvg.setText("平均分："+avg);

        pieDataList.add(new PieEntry(one,"不及格"));
        pieDataList.add(new PieEntry(two,"及格"));
        pieDataList.add(new PieEntry(three,"良好"));
        pieDataList.add(new PieEntry(four,"优秀"));
        pieDataList.add(new PieEntry(five,"满绩点"));


        PieDataSet pieDataSet=new PieDataSet(pieDataList,"");
        PieData pieData=new PieData(pieDataSet);
        pie.setData(pieData);

        pie.setBackgroundColor(Color.WHITE);
        pie.setExtraOffsets(0f,10f,0f,10f);

        //设置各个数据的颜色
        pieDataSet.setColors(colors);
        //实体扇形的空心圆的半径   设置成0时就是一个圆 而不是一个环
        pie.setHoleRadius(0);
        //中间半透明白色圆的半径    设置成0时就是隐藏
        pie.setTransparentCircleRadius(0);
        //设置描述的字体大小
        pie.setEntryLabelTextSize(10);
        pie.setEntryLabelColor(Color.BLACK);
        //设置数据的字体大小
        pieDataSet.setValueTextSize(12);
        //设置描述的位置
        pieDataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        pieDataSet.setValueLinePart1Length(0.8f);//设置描述连接线长度

        //设置数据的位置
        pieDataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        pieDataSet.setValueLinePart2Length(0.8f);//设置数据连接线长度
        //设置两根连接线的颜色
        pieDataSet.setValueLineColor(Color.BLACK);


        //对于右下角一串字母的操作
        pie.getDescription().setEnabled(true);                  //是否显示右下角描述
        pie.getDescription().setText("成绩统计");    //修改右下角字母的显示
        pie.getDescription().setTextSize(13);                    //字体大小
        pie.getDescription().setTextColor(Color.RED);             //字体颜色


        //数据更新
        pie.notifyDataSetChanged();
        pie.invalidate();

        //动画（如果使用了动画可以则省去更新数据的那一步）
        pie.animateY(3000); //在Y轴的动画  参数是动画执行时间 毫秒为单位

    }

    //初始化点击事件
    private void initClick(){
        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!test_name.equals("暂无考试") && !test_name.equals("网络错误")){
                    ScoreModel.selectScores(ownClass.getId(), test_name, new ScoreListCallBack() {
                        @Override
                        public void onSuccess(List<Score> scoreList) {
                            scores.clear();
                            scores = scoreList;
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    setPieChartAndAvg(scores);
                                }
                            });
                        }

                        @Override
                        public void onFailed() {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(activity, "1、查询失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                    ScoreModel.selectScoreMax(ownClass.getId(), test_name, new StringCallBack() {
                        @Override
                        public void onSuccess(final String result) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    binding.textMax.setText("最高分："+result);
                                }
                            });
                        }

                        @Override
                        public void onFailed() {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    binding.textMax.setText("最高分：NULL");
                                    Toast.makeText(activity, "2、查询失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });

                }else{
                    Toast.makeText(activity, "请输入考试名称或网络错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
